<template>
	<view class="content">
		<view class="top1"><view class="top2">消息</view></view>
		<view style="height: 176upx;"></view>
		<!-- 头部 -->
		<view class="navbar">
			<view
				v-for="(item, index) in navList"
				:key="index"
				class="nav-item"
				:class="{ current: tabCurrentIndex === index }"
				@click="tabClick(index)"
			>
				{{ item.text }}
			</view>
		</view>

		<!-- 显示区域 -->
		<view class="nav_item mar-top-20" v-if="tabCurrentIndex == 0">
			<vlew
				class="flex content-item"
				v-for="(item, index) in conversationList"
				:key="index"
				@tap="toMessage(item)"
			>
				<view class="userimg">
					<image :src="item.userProfile.avatar" style="border-radius: 50%!important;"></image>
				</view>
				<view class="flex-1 mar-left-20">
					<view class="flex aic">
						<view class="flex-1">
							<text class="fs-32 fc-33">{{ item.userProfile.nick }}</text>
							<text class="fc-66 fs-26 mar-left-20">{{ item.content }}</text>
						</view>
						<view class="fc-99 fs-24">{{ getLocalTime(item.lastMessage.lastTime) }}</view>
					</view>
					<view class="flex mar-top-10">
						<text class="fc-99 fs-28">[送达]</text>
						<view class="flex-1 fc-33 fs-28 one-ellipsis mar-left-5 mar-right-10">
							{{ item.lastMessage.messageForShow }}
						</view>
						<view
							class="tops-t fs-24"
							style="border-radius: 17rpx;padding:0 4rpx"
							v-if="item.unreadCount > 99"
						>
							99+
						</view>
						<view class="tops-t fs-24" v-else>{{ item.unreadCount }}</view>
					</view>
				</view>
			</vlew>
		</view>
		<view class="nav_item mar-top-20" v-if="tabCurrentIndex == 1">
			<vlew class="flex content-item" v-for="(item, index) in newsList" :key="index">
				<view class="userimg"><image :src="item.portrait" style="border-radius: 50%!important;"></image></view>
				<view class="flex-1 mar-left-20">
					<view class="flex">
						<view class="flex-1">
							<text class="fs-32 fc-33">{{ item.name }}</text>
							<!-- <text class="fc-66 fs-26 mar-left-20">{{ item.jobs }}</text> -->
						</view>
						<view class="fc-99 fs-24">{{ getLocalTime(item.time) }}</view>
					</view>
					<view class="flex mar-top-10">
						<view class="fc-33 fs-28 one-ellipsis mar-left-5 w-490">{{ item.content }}</view>
						<view class="fc-66 fs-24 mar-top-15">回复了您的帖子 {{ item.reply }}</view>
					</view>
				</view>
			</vlew>
		</view>
		<view class="nav_item mar-top-20" v-if="tabCurrentIndex == 2">
			<vlew class="flex content-item" v-for="(item, index) in platformNews" :key="index">
				<view class="userimg"><image :src="item.portrait" style="border-radius: 50%!important;"></image></view>
				<view class="flex-1 mar-left-20">
					<view class="flex">
						<view class="flex-1">
							<text class="fs-32 fc-33">{{ item.name }}</text>
							<!-- <text class="fc-66 fs-26 mar-left-20">{{ item.jobs }}</text> -->
						</view>
						<view class="fc-99 fs-24">{{ getLocalTime(item.time) }}</view>
					</view>
					<view class="flex mar-top-10">
						<view class="fc-33 fs-28 two-ellipsis mar-left-5 w-490">{{ item.reply }}</view>
					</view>
				</view>
			</vlew>
		</view>
	</view>
</template>

<script>
import { setTokenStorage } from '../../utils/token'
import logger from '../../utils/logger'
import { genTestUserSig } from '../../debug/GenerateTestUserSig.js'
const { getTokenStorage } = require('../../utils/token.js')
const app = getApp()

export default {
	data() {
		return {
			conversationList: [
				{
					jobs: '产品助理',
					userProfile: {
						avatar: '',
						nick: '吴先生'
					},
					lastMessage: {
						lastTime: 1660202928661,
						messageForShow: '你好，我们最近在招客服，你可以来面试吗'
					},
					unreadCount: 10
				},
				{
					jobs: '数码科技 · HR',
					userProfile: {
						avatar: '',
						nick: '吴先生'
					},
					lastMessage: {
						lastTime: 1660060800000,
						messageForShow: '你好，我们最近在招客服，你可以来面试吗'
					},
					unreadCount: 9
				},
				{
					jobs: 'UI设计',
					userProfile: {
						avatar: '',
						nick: '吴先生'
					},
					lastMessage: {
						lastTime: 1657123200000,
						messageForShow: '你好，我们最近在招客服，你可以来面试吗'
					},
					unreadCount: 200
				}
			], // 会话列表
			firstLoading: true,
			userID: '',
			timUserId: '',
			timSign: '',
			tabCurrentIndex: 0,
			navList: [
				{
					state: 0, //state为切换内容
					text: '求职'
				},
				{
					state: 1,
					text: '帖子'
				},
				{
					state: 2,
					text: '平台'
				}
			],
			newsList: [
				{
					portrait: '',
					name: '吴先生',
					reply: '回复了您的帖子《关国设下计谋，用娘炮文化亚塑日本，已影响至今》',
					content: '很有道理，逻辑清晰。',
					time: 1660202928661
				},
				{
					portrait: '',
					name: '吴先生',
					reply: '回复了您的帖子《关国设下计谋，用娘炮文化亚塑日本，已影响至今》',
					content: '不错不错。',
					time: 1660060800000
				},
				{
					portrait: '',
					name: '吴先生',
					reply: '回复了您的帖子《关国设下计谋，用娘炮文化亚塑日本，已影响至今》',
					content: '写的很好。',
					time: 1657123200000
				}
			],
			platformNews: [
				{
					portrait: '',
					name: '平台克服',
					reply: ' 你好，我的问题我们已经处理好了...',
					content: '很有道理，逻辑清晰。',
					time: 1660202928661
				},
				{
					portrait: '',
					name: '帖子审核',
					reply: '审核通过您的帖子(COPIED_ MB _WIDGET)已审核通过...',
					content: '不错不错。',
					time: 1660060800000
				},
				{
					portrait: '',
					name: '签到成功',
					reply: '恭喜您签到成功，获得宅币+10',
					content: '写的很好。',
					time: 1657123200000
				}
			]
		}
	},
	async mounted() {
		return
		console.log('mounted...')
		let userInfo = uni.getStorageSync('userInfo')

		// 监听会话列表
		uni.$TUIKit.on(uni.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated)
		uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady)
		this.firstLoading = false

		await this.getMySig(userInfo.id)
		await this.loginTim()
	},
	onShow() {
		console.log('onshow...')
	},
	onLoad(options) {
		console.log('onload...')
		// 页面显示是默认选中第一个
		this.tabCurrentIndex = 0
	},

	methods: {
		/* 跳转消息页 */
		toMessage(item) {
			console.log('chat item', item)
			//conversationID
			uni.navigateTo({
				url:
					'/pages/chat/chat_detail?conversationID=' +
					item.conversationID +
					'&userID=' +
					item.userProfile.userID
			})
		},
		//顶部tab切换
		tabClick(index) {
			this.tabCurrentIndex = index
		},
		getLocalTime(nS) {
			// return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')
			// return new Date(nS).toLocaleString().replace(/:\d{1,2}$/, ' ')
			let nowTime = new Date().getTime()
			let day = Math.floor(Math.abs(nowTime - nS) / 1000 / 60 / 60 / 24)
			let time = new Date(nS).toLocaleString()
			if (day == 0) return time.replace(/\d{4}\/\d{1,2}\/\d{1,2}/, '').replace(/:\d{1,2}$/, '')
			else if (day == 1) return '昨天'
			else return time.match(/\d{4}\/\d{1,2}\/\d{1,2}/)[0]
		},
		// 监听会话列表
		onConversationListUpdated(event) {
			console.log('event', event)
			this.conversationList = event.data
			console.log('onConversationListUpdated this.conversationList:', this.conversationList)
			logger.log('TUI-conversation | onConversationListUpdated  |ok')
			this.setData({
				conversationList: event.data
			})
		},
		// 获取会话列表
		getConversationList() {
			uni.$TUIKit.getConversationList().then(imResponse => {
				console.log('imResponse', imResponse)
				this.conversationList = imResponse.data.conversationList
				console.log('getConversationList this.conversationList:', this.conversationList)
				logger.log(
					`TUI-conversation | getConversationList | getConversationList-length: ${
						imResponse.data.conversationList.length
					}`
				)
				logger.log(`会话列表: ${imResponse.data.conversationList}`)
				this.setData({
					conversationList: imResponse.data.conversationList
				})
			})
		},

		updateMyProfile() {
			let userInfo = uni.getStorageSync('userInfo')
			const promise = uni.$TUIKit.updateMyProfile({
				nick: userInfo.nickname,
				userID: userInfo.openid,
				avatar: userInfo.avatar
			})
			promise
				.then(imResponse => {
					this.setData({
						userInfo: imResponse.data,
						popupToggle: false
					})
				})
				.catch(imError => {
					this.setData({
						popupToggle: false
					})
					console.warn('updateMyProfile error:', imError) // 更新资料失败的相关信息
				})
		},
		onSDKReady({ name }) {
			const isSDKReady = name === uni.$TUIKitEvent.SDK_READY ? true : false
			uni.$emit('isSDKReady', {
				isSDKReady: true
			})
			this.updateMyProfile()
			this.getConversationList()
		},
		async getMySig(id) {
			let sigInfo = await this.$apis.getMySig(id)
			this.timUserId = sigInfo.data.imIdentifier
			this.timSign = sigInfo.data.sig
		},

		async loginTim() {
			const userID = this.timUserId
			const userSig = this.timSign
			const SDKAppID = 1400689974
			logger.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`)
			// #ifdef  APP-PLUS
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-APP',
				ext2: 'uniTuikitExternal',
				ext3: `${SDKAppID}`
			})
			// #endif
			// #ifdef MP-WEIXIN
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-MP-WEIXIN',
				ext2: 'uniTuikitExternal',
				ext3: `${SDKAppID}`
			})
			// #endif
			// #ifdef H5
			uni.$aegis.reportEvent({
				name: 'platform',
				ext1: 'platform-H5',
				ext2: 'uniTuikitExternal',
				ext3: `${SDKAppID}`
			})
			uni.showToast({
				title: 'TUIKit 暂不支持 H5 / web ，请使用者自己完成兼容哦～ ',
				icon: 'none',
				duration: 3000
			})
			// #endif
			app.globalData.userInfo = {
				userSig,
				userID
			}
			setTokenStorage({
				userInfo: app.globalData.userInfo
			})
			wx.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true)

			uni.$TUIKit
				.login({
					userID: userID,
					userSig: userSig
				})
				.then(() => {
					this.getConversationList()
					// uni.$aegis.reportEvent({
					//     name: 'login',
					//     ext1: 'login-success',
					//     ext2: 'uniTuikitExternal',
					//     ext3: `${SDKAppID}`,
					// })
				})
				.catch(error => {
					console.log(error)
					// uni.$aegis.reportEvent({
					//     name: 'login',
					//     ext1: `login-failed#error:${error}`,
					//     ext2: 'uniTuikitExternal',
					//     ext3: `${SDKAppID}`,
					// })
				})

			// 登录原生插件
			// #ifdef APP-PLUS
			if (typeof uni.$TUICalling == 'undefined') {
				uni.showToast({
					title: '如果需要音视频功能，请集成插件使用真机运行并且自定义基座调试哦～',
					icon: 'none',
					duration: 3000
				})
				logger.error(
					'请使用真机运行并且自定义基座调试，否则影响音视频功能～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use'
				)
			} else {
				uni.$TUICalling.login(
					{
						sdkAppID: SDKAppID,
						userID: userID,
						userSig: userSig
					},
					res => {
						console.log(JSON.stringify(res.msg))
						uni.showToast({
							title: 'login',
							icon: 'none'
						})
					}
				)
			}
			// #endif

			// if (this.path && this.path !== 'undefined') {
			// 	uni.redirectTo({
			// 		url: this.path
			// 	});
			// } else {
			// 	uni.switchTab({
			// 		url: '../TUI-Index/index'
			// 	});
			// }
		}
	}
}
</script>

<style lang="scss" scoped>
.top1 {
	background: #84c0f4;
	position: fixed;
	height: 176upx;
	width: 100%;
	z-index: 10000;
	display: flex;

	.top2 {
		padding-top: 88upx;
		width: 100%;
		font-weight: 400;
		color: #ffffff;
		font-size: 34upx;
		font-family: Source Han Sans CN-Regular, Source Han Sans CN;
		text-align: center;
	}
}
page,
.content {
	background: #fff;
	height: 100%;
}

.swiper-box {
	height: calc(100% - 40px);
}
.list-scroll-content {
	height: 100%;
}

.navbar {
	display: flex;
	height: 40px;
	padding: 0 5px;
	background: #fff;
	box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
	position: relative;
	z-index: 10;
	.nav-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		font-size: 15px;
		color: #333;
		position: relative;
		&.current {
			color: #84c0f4;
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				width: 44px;
				height: 0;
				border-bottom: 2px solid #84c0f4;
			}
		}
	}
}
.nav_item {
	.content-item {
		padding: 20rpx 32rpx;
		border-bottom: 1px solid #eeeeee;
		.userimg {
			width: 96rpx;
			height: 96rpx;
			border-radius: 50%;
			opacity: 1;
			display: flex;
			align-items: center;
			overflow: hidden image {
				width: 100%;
				height: 100%;
				display: block;
			}
		}
		.w-190 {
			width: 190rpx;
		}
		.w-490 {
			width: 490rpx;
		}
		.tops-t {
			min-width: 34rpx;
			height: 34rpx;
			background: #f25643;
			line-height: 34rpx;
			text-align: center;
			color: #fff;
			border-radius: 50%;
		}
	}
}
</style>
